<template>
  <div class="user-detail">
    <el-dropdown>
      <span class="el-dropdown-link">
        <el-avatar :size="36" :src="avatarUrl" :key="avatarKey" @click.native="handleAvatarClick">
          {{ displayName.charAt(0)?.toUpperCase() }}
        </el-avatar>
        <span class="username">{{ displayName }}</span>
        <el-icon><arrow-down /></el-icon>
      </span>

      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="showProfile">
            <el-icon>
              <User />
            </el-icon> 个人中心
          </el-dropdown-item>
          <el-dropdown-item @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon> 退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 头像修改对话框 -->
    <avatar-dialog v-model="dialogVisible" @success="handleAvatarUpdate" />
  </div>
</template>

<script>
import { ArrowDown, User, SwitchButton } from '@element-plus/icons-vue'
import AvatarDialog from './AvatarDialog.vue'

export default {
  name: 'UserDetail',
  components: {
    ArrowDown,
    User,
    SwitchButton,
    AvatarDialog
  },
  props: {
    showAction: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      avatarKey: 0,
      dialogVisible: false
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user?.userInfo || {}
    },
    avatarUrl() {
      return this.userInfo.avatar || require('@/assets/images/baichuan.png')
    },
    displayName() {
      return this.userInfo.nickname || this.userInfo.username || '未登录'
    }
  },
  methods: {
    handleAvatarClick() {
      if (this.showAction) {
        this.dialogVisible = true
      }
    },
    showProfile() {
      this.$router.push('/profile')
    },
    logout() {
      this.$store.dispatch('user/logout').then(() => {
        this.$router.push('/login')
      })
    },
    handleAvatarUpdate(newAvatar) {
      this.avatarKey++
      this.$emit('avatar-updated', newAvatar)
    }
  }
}
</script>

<style scoped>
.user-detail {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 10px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>